import os

from flask import Flask, jsonify, request
import difflib
import datetime

app = Flask(__name__)
# app.debug = True

@app.route('/apis/diff/', methods=['POST'])
def diff():
    data = request.get_json()
    global basePath
    if data['tag'] == 'old2cur':
        ## 开发时使用
        #basePath = os.path.dirname(os.path.abspath(__file__))
        srcPath = os.path.join('/old_dir', '') + os.path.join(*data['src'])
        destPath = os.path.join('/cur_dir', '') + os.path.join(*data['dest'])
    elif data['tag'] == 'cur2target':
        ## 开发时使用
        #basePath = os.path.dirname(os.path.abspath(__file__))
        srcPath = os.path.join('/cur_dir', '') + os.path.join(*data['src'])
        destPath = os.path.join('/local_dir', '') + os.path.join(*data['dest'])
    else:
        srcPath = os.path.dirname(os.path.abspath(__file__))
        destPath = os.path.dirname(os.path.abspath(__file__))

    # print("srcPath:",srcPath, " destPath:", destPath)


    res = []

    try:
        # 读取文件内容
        with open(srcPath, mode='rt',encoding="utf-8") as f1, open(destPath, mode='rt',encoding="utf-8") as f2:
            content1 = f1.read()
            content2 = f2.read()
    except Exception as e:
        print("Error reading files:", e)
        return str(e)

    # 使用difflib进行比较
    diff = difflib.unified_diff(content1.splitlines(), content2.splitlines(), fromfile=os.path.basename(srcPath), tofile=os.path.basename(destPath),lineterm=' ')
    diff_list = list(diff)
    try:
        if diff_list:
            diff_result = '\n'.join(diff_list)  # 将结果转换为字符串
            res.append(diff_result)
        else:
            print("No differences found")
            res.append("No differences found")
    except Exception as e:
        print("e:", e)
        return str(e)

    # print("res", repr('\n'.join(res)))
    # return ' '.join(res)
    return jsonify({'diff_result': '\n'.join(res)})



"""
    获取目录树
"""
@app.route('/apis/dirtree/', methods=['GET'])
def get_yaml_files_tree(root_dir=os.path.dirname(os.path.abspath(__file__))):
    root_dir = request.values.get('base_dir')
    def build_tree(path):
        tree = []
        for root, dirs, files in os.walk(path):
            # Filter only .yml and .yaml files
            yaml_files = [f for f in files if f.endswith(('.yml', '.yaml'))]

            # Initialize node for current directory
            node = {
                'label': os.path.basename(root),
                'value': os.path.basename(root),
                'children': []
            }

            # Recursively add children directories
            for d in dirs:
                child_path = os.path.join(root, d)
                child_tree = build_tree(child_path)
                if child_tree:
                    node['children'].append({
                        'label': d,
                        'value': d,
                        'children': child_tree
                    })

            # Add yaml files to the children
            for f in yaml_files:
                node['children'].append({
                    'label': f,
                    'value': f
                })

            # Only append node if it has children
            if node['children']:
                tree.append(node)
                break  # Stop further os.walk() since we found our relevant directory and its children

        return node['children']

    return build_tree(root_dir)


# 获取配置文件内容
@app.route('/apis/getconfigfile/', methods=['POST'])
def getConfigFile():
    data = request.get_json()


    ## 开发环境调试的时候开启
    #basePath = 'D:\\PycharmProjects\\config-backend'

    ### 正式环境的时候开启
    basePath = '/local_dir'

    filePath = os.path.join(basePath, '') + os.path.join(*data['path'])


    with open(filePath, mode='r', encoding="utf-8") as f1:
        content1 = f1.read()
    return content1

# 修改配置文件内容
@app.route('/apis/commitconfigfile/', methods=['POST'])
def commitConfigFile():
    data = request.get_json()

    ## 开发测试使用
    #basePath = 'D:\\PycharmProjects\\config-backend'
    #backPath = 'D:\\PycharmProjects\\config-backend'

    ## 正式上线启用
    basePath = '/local_dir'
    backPath = '/backup'

    filePath = os.path.join(basePath, '') + os.path.join(*data['path'])

    try:
        ## 先将原来的保存一份
        nowTime = datetime.datetime.now()
        with open(filePath, 'r', encoding='utf-8') as f:
            with open(os.path.join(backPath, '') + data['path'][-1] + '_' + nowTime.strftime('%m%d%H%M%S'), 'w',
                      encoding='utf-8') as f2:
                f2.write(f.read())

        ## 再更新文件
        with open(filePath, mode='w', encoding="utf-8") as f1:
            f1.write(data['code'])
    except Exception as e:
        return jsonify({"msg": str(e), "type": "error"})
    return jsonify({"message": "文件修改成功", "type": "success"})



if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
